package vn.lumi.smarthome.ui;

import java.util.Calendar;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;

import vn.lumi.smarthome.ActivityHelper;
import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Schedule;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.AddScheduleActivity.ViewHolder;
import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.R.integer;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ToggleButton;

public class EditScheduleActivity extends SherlockFragmentActivity implements
		OnClickListener, LoaderCallbacks<Cursor> {

	private String TAG = "EditScheduleActivity";
	public static final String EXTRA_DEVICE_ID = "device id";
	public static final String EXTRA_DEVICE_NAME = "device name";
	public static final String EXTRA_DEVICE_TYPE = "device type";
	public static final String EXTRA_SCHEDULE_ID = "schedule id";
	private static final String SCHEDULE_ID = "schedule id";
	private static final int LOADER_ID = 5;

	private int deviceId;
	private String deviceName;
	private int deviceType;
	private int scheduleId;

	// public static final String DEVICE_ID = "device_id";
	// public static final String STATE = "state";
	// public static final String REPEAT = "repeat";
	// public static final String MONDAY = "monday";
	// public static final String TUESDAY = "tuesday";
	// public static final String WEDNESDAY = "wednesday";
	// public static final String THURSDAY = "thursday";
	// public static final String FRIDAY = "friday";
	// public static final String SATURDAY = "saturday";
	// public static final String SUNDAY = "sunday";
	// public static final String HOUR = "hour";
	// public static final String MINUTE = "minute";
	// public static final String DURATION = "duration";
	// public static final String STATE_ID = "state_id";

	// isNow de biet xem gui goi tin schedule sang HC la bay gio hay khong?
	private boolean isNow = true;

	// --------------Hieuph modify
	private TextView txvDescription;
	private TextView txvSave;
	private ListView lsv_schedule;
	MyAdapter myApdater;

	private boolean mT2 = false;
	private boolean mT3 = false;
	private boolean mT4 = false;
	private boolean mT5 = false;
	private boolean mT6 = false;
	private boolean mT7 = false;
	private boolean mCn = false;

	// parameters of old scene
	private int oldScheduleState;
	private int mOldTurnOnHour;
	private int mOldTurnOnMinute;
	private int mOldTurnOffHour;
	private int mOldTurnOffMinute;
	private int mOldRepeat;
	private int mOldMonday, mOldTuesday, mOldWednesday, mOldThursday,
			mOldFriday, mOldSaturday, mOldSunday;
	private int deviceStateId;
	private int mOldDeviceState;

	// parameters new
	private int mNewTurnOnHour;
	private int mNewTurnOnMinute;
	private int mNewTurnOffHour;
	private int mNewTurnOffMinute;

	protected TextView tvPickertimeOn;
	protected ImageView imv_picker_time_on;
	protected TextView tvPickertimeOff;
	protected ImageView imv_picker_time_off;
	protected ToggleButton tgbScheduleOn;
	protected ToggleButton tgbScheduleOff;

	// -------------------------------------------------

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Config.configLanguage(getBaseContext(),
				Preference.getLanguage(getApplicationContext()));// Thiet lap
																	// ngon ngu
		setContentView(R.layout.activity_schedule_base_new);

		Intent i = getIntent();
		deviceName = i.getStringExtra(EXTRA_DEVICE_NAME);
		scheduleId = i.getIntExtra(EXTRA_SCHEDULE_ID, -1);
		deviceId = i.getIntExtra(EXTRA_DEVICE_ID, -1);
		deviceType = i.getIntExtra(EXTRA_DEVICE_TYPE, -1);
		setupActionbar();

		Bundle bundle = new Bundle();
		bundle.putInt(SCHEDULE_ID, scheduleId);
		this.getSupportLoaderManager().initLoader(LOADER_ID, bundle, this);

		lsv_schedule = (ListView) findViewById(R.id.activity_schedule_base_listview);
		myApdater = new MyAdapter();
		lsv_schedule.setAdapter(myApdater);
		init_view();

		ActivityHelper.initialize(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Config.isVibrate = Preference.getVibrate(this);
//		Config.configLanguage(getBaseContext(),
//				Preference.getLanguage(getApplicationContext()));// Thiet lap
//																	// ngon ngu
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		if (Config.isVibrate)
			new VibrateThread(getApplicationContext()).start();
	}

	private void init_view() {

		// ============== Hieuph modidy

		tvPickertimeOn = (TextViewCustom) findViewById(R.id.activity_schedule_base_tv_picker_time_on);
		imv_picker_time_on = (ImageView) findViewById(R.id.activity_schedule_base_img_picker_time_on);
		imv_picker_time_on.setOnClickListener(this);
		tvPickertimeOff = (TextViewCustom) findViewById(R.id.activity_schedule_base_tv_picker_time_off);
		imv_picker_time_off = (ImageView) findViewById(R.id.activity_schedule_base_img_picker_time_off);
		imv_picker_time_off.setOnClickListener(this);
		tgbScheduleOff = (ToggleButton) findViewById(R.id.activity_schedule_base_tbg_time_turnOff);
		tgbScheduleOn = (ToggleButton) findViewById(R.id.activity_schedule_base_tbg_time_turnOn);
		tgbScheduleOn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				if (tgbScheduleOn.isChecked()) {
					tvPickertimeOn.setEnabled(true);
					imv_picker_time_on.setEnabled(true);
					tgbScheduleOn.setBackgroundResource(R.drawable.img_tickon);
					Calendar c = Calendar.getInstance();
					int hour = c.get(Calendar.HOUR_OF_DAY);
					int minute = c.get(Calendar.MINUTE);
					tvPickertimeOn.setText(AbstractSceneActivity
							.padding_str(hour)
							+ ":"
							+ AbstractSceneActivity.padding_str(minute));
					mNewTurnOnHour = hour;
					mNewTurnOnMinute = minute;

				} else {
					tvPickertimeOn.setEnabled(false);
					imv_picker_time_on.setEnabled(false);
					tgbScheduleOn.setBackgroundResource(R.drawable.img_tickoff);
					tvPickertimeOn.setText("");
				}
			}
		});
		tgbScheduleOff.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				if (tgbScheduleOff.isChecked()) {
					tvPickertimeOff.setEnabled(true);
					imv_picker_time_off.setEnabled(true);
					tgbScheduleOff.setBackgroundResource(R.drawable.img_tickon);
					Calendar c = Calendar.getInstance();
					int hour = c.get(Calendar.HOUR_OF_DAY);
					int minute = c.get(Calendar.MINUTE);
					tvPickertimeOff.setText(AbstractSceneActivity
							.padding_str(hour)
							+ ":"
							+ AbstractSceneActivity.padding_str(minute));
					mNewTurnOffHour = hour;
					mNewTurnOffMinute = minute;

				} else {
					tvPickertimeOff.setEnabled(false);
					imv_picker_time_off.setEnabled(false);
					tgbScheduleOff
							.setBackgroundResource(R.drawable.img_tickoff);
					tvPickertimeOff.setText("");
				}
			}
		});
		txvDescription = (TextView) findViewById(R.id.activity_schedule_base_txv_description);
		txvDescription.setText(getApplicationContext().getString(
				R.string.txt_schedule)
				+ deviceName);
		// -------------------------------------------------
	}

	private void setupActionbar() {
		ActionBar actionbar = getSupportActionBar();
		actionbar.setCustomView(R.layout.actionbar_setting_activity);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayShowTitleEnabled(false);
		txvSave = (TextView) findViewById(R.id.actionbar_setting_activity_logout);
		txvSave.setText(getString(R.string.txt_save));
		txvSave.setTextSize(17);
		txvSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				editSchedule();
			}
		});
		TextView tvCreatScedule = (TextView) findViewById(R.id.actionbar_setting_activity_set);
		tvCreatScedule.setText(getString(R.string.txt_schedule_edit));
		tvCreatScedule.setTextSize(17);
	}

	private void init_data() {
		// schedule type
		// Hieuph modify
		setT2(this.mOldMonday == Schedule.SCHEDULE_DAY_ON);
		setT3(this.mOldTuesday == Schedule.SCHEDULE_DAY_ON);
		setT4(this.mOldWednesday == Schedule.SCHEDULE_DAY_ON);
		setT5(this.mOldThursday == Schedule.SCHEDULE_DAY_ON);
		setT6(this.mOldFriday == Schedule.SCHEDULE_DAY_ON);
		setT7(this.mOldSaturday == Schedule.SCHEDULE_DAY_ON);
		setCn(this.mOldSunday == Schedule.SCHEDULE_DAY_ON);
		myApdater.notifyDataSetChanged();

		if (this.mOldTurnOffHour == Schedule.SCHEDULE_NOT_TURNOFF_TYPE) {
			tgbScheduleOff.setChecked(false);
			tvPickertimeOff.setEnabled(false);
			imv_picker_time_off.setEnabled(false);
			tgbScheduleOff.setBackgroundResource(R.drawable.img_tickoff);
			tvPickertimeOff.setText("");

		} else {
			tgbScheduleOff.setChecked(true);
			tvPickertimeOff.setEnabled(true);
			imv_picker_time_off.setEnabled(true);
			tgbScheduleOff.setBackgroundResource(R.drawable.img_tickon);
			mNewTurnOffHour = mOldTurnOffHour;
			mNewTurnOffMinute = mOldTurnOffMinute;
			tvPickertimeOff.setText(AbstractSceneActivity
					.padding_str(mNewTurnOffHour)
					+ ":"
					+ AbstractSceneActivity.padding_str(mNewTurnOffMinute));
		}

		if (this.mOldTurnOnHour == Schedule.SCHEDULE_NOT_TURNON_TYPE) {
			tgbScheduleOn.setChecked(false);
			tvPickertimeOn.setEnabled(false);
			imv_picker_time_on.setEnabled(false);
			tgbScheduleOn.setBackgroundResource(R.drawable.img_tickoff);
			tvPickertimeOn.setText("");
		} else {
			tgbScheduleOn.setChecked(true);
			tvPickertimeOn.setEnabled(true);
			imv_picker_time_on.setEnabled(true);
			tgbScheduleOn.setBackgroundResource(R.drawable.img_tickon);
			mNewTurnOnHour = mOldTurnOnHour;
			mNewTurnOnMinute = mOldTurnOnMinute;
			tvPickertimeOn.setText(AbstractSceneActivity
					.padding_str(mNewTurnOnHour)
					+ ":"
					+ AbstractSceneActivity.padding_str(mNewTurnOnMinute));
		}

		// -------------

	}

	private void editSchedule() {
		if (tgbScheduleOff.isChecked() || tgbScheduleOn.isChecked()) {
			boolean isRepeatChanged = false;
			boolean repeatBoolean = false;
			boolean[] daysBoolean = new boolean[7];
			daysBoolean[0] = getT2();
			daysBoolean[1] = getT3();
			daysBoolean[2] = getT4();
			daysBoolean[3] = getT5();
			daysBoolean[4] = getT6();
			daysBoolean[5] = getT7();
			daysBoolean[6] = getCn();
			int[] daysInt = new int[7];
			for (int i = 0; i < 7; i++) {
				if (daysBoolean[i] == true)
					daysInt[i] = Schedule.SCHEDULE_DAY_ON;
				else
					daysInt[i] = Schedule.SCHEDULE_DAY_OFF;
			}
			if (getT2() || getT3() || getT4() || getT5() || getT6() || getT7()
					|| getCn())
				repeatBoolean = true;

			if (daysInt[0] == this.mOldMonday && daysInt[1] == this.mOldTuesday
					&& daysInt[2] == this.mOldWednesday
					&& daysInt[3] == this.mOldThursday
					&& daysInt[4] == this.mOldFriday
					&& daysInt[5] == this.mOldSaturday
					&& daysInt[6] == this.mOldSaturday)
				isRepeatChanged = false;
			else
				isRepeatChanged = true;
			Log.d(TAG, "isRepeatChanged=" + isRepeatChanged);

			// Turn on
			if (!tgbScheduleOn.isChecked()) {
				mNewTurnOnHour = Schedule.SCHEDULE_NOT_TURNON_TYPE;
				mNewTurnOnMinute = Schedule.SCHEDULE_NOT_TURNON_TYPE;
			} else {
				// day la truong hop bat ngay thiet bi.Neu bat ngay thiet bi
				// them 1 vao bit cao nhat
				if (mNewTurnOnHour == AddScheduleActivity.getTimeSytem()
						.getHour()
						&& mNewTurnOnMinute == AddScheduleActivity
								.getTimeSytem().getMinute()) {
					// Them 1 vao bit dau tien cua byte mTurnOnHour
					mNewTurnOnHour = mNewTurnOnHour | 128;
				}
			}
			boolean isTurnOnChanged = false;
			if (mNewTurnOnHour == this.mOldTurnOnHour
					&& mNewTurnOnMinute == this.mOldTurnOnMinute)
				isTurnOnChanged = false;
			else
				isTurnOnChanged = true;
			Log.d(TAG, "isTurnOnChanged=" + isTurnOnChanged);

			// Turn Off
			boolean isTurnOffChanged = false;
			if (!tgbScheduleOff.isChecked()) {
				mNewTurnOffHour = Schedule.SCHEDULE_NOT_TURNOFF_TYPE;
				mNewTurnOffMinute = Schedule.SCHEDULE_NOT_TURNOFF_TYPE;
			}
			if (mNewTurnOffHour == this.mOldTurnOffHour
					&& mNewTurnOffMinute == this.mOldTurnOffMinute)
				isTurnOffChanged = false;
			else
				isTurnOffChanged = true;

			Log.d(TAG, "isDurationChanged=" + isTurnOffChanged);

			if (isRepeatChanged == false && isTurnOnChanged == false
					&& isTurnOffChanged == false)
				finish();
			else {
				ContentValues values = new ContentValues();
				values.put("isNow", isNow);
				values.put("Schedule id", this.scheduleId);
				values.put("Device Id", this.deviceId);
				values.put("Repeat", repeatBoolean);
				values.put("Monday", daysBoolean[0]);
				values.put("Tuesday", daysBoolean[1]);
				values.put("Wednesday", daysBoolean[2]);
				values.put("Thursday", daysBoolean[3]);
				values.put("Friday", daysBoolean[4]);
				values.put("Saturday", daysBoolean[5]);
				values.put("Sunday", daysBoolean[6]);
				values.put("Turn on hour", mNewTurnOnHour);
				values.put("Turn on minute", mNewTurnOnMinute);
				values.put("Turn off hour", mNewTurnOffHour);
				values.put("Turn off minute", mNewTurnOffMinute);

				if (deviceType == Device.DEVICE_TYPE_LIGHT
						|| deviceType == Device.DEVICE_TYPE_HEATER
						|| deviceType == Device.DEVICE_TYPE_AIRCON)
					values.put("Dev_state", Device.DEVICE_STATE_DEVICE_ON);
				else if (deviceType == Device.DEVICE_TYPE_HOR_BLIND
						|| deviceType == Device.DEVICE_TYPE_VER_BLIND) {
					values.put("Dev_state", Device.DEVICE_STATE_BLIND_MAX_LEVEL);
				} else if (deviceType == Device.DEVICE_TYPE_DIMMER) {
					values.put("Dev_state", Device.DEVICE_STATE_DIMMER_ON);
				} else if (deviceType == Device.DEVICE_TYPE_RGB) {
					values.put("Dev_state", Device.DEVICE_STATE_RGB_ON);
				}

				getApplicationContext().getContentResolver().update(
						TBL_Schedule.CONTENT_URI_SCHEDULE_EDIT, values, null,
						null);

				// show dialog
				ProgressDialog dialog = new ProgressDialog(
						new ContextThemeWrapper(this, R.style.AlertDialogCustom));
				dialog.setMessage(getString(R.string.txt_saving_schedule_in_HC));
				dialog.setCancelable(false);
				dialog.show();
				// Thay doi font chu cua Dialog
				ChangeFont changeFont = new ChangeFont(getApplicationContext());
				TextView textView = (TextView) dialog
						.findViewById(android.R.id.message);
				textView = changeFont.changeFontTextView(textView,
						R.string.txt_saving_schedule_in_HC, LumiHome.font,
						LumiHome.sizeContent, Gravity.NO_GRAVITY,
						getResources().getColor(R.color.greenActionbar));
				// set broadcast receiver
				EditScheduleReceiver mReceiver = new EditScheduleReceiver(
						dialog);
				IntentFilter filter = new IntentFilter();
				filter.addAction(getApplicationContext().getString(
						R.string.txt_broadcast_edit_schedule_successful));
				filter.addAction(getApplicationContext().getString(
						R.string.txt_broadcast_edit_schedule_failed));
				filter.addAction(getApplicationContext().getString(
						R.string.txt_broadcast_edit_schedule_overload));
				this.registerReceiver(mReceiver, filter);
			}
		} else {
			showCustomDialogBoth(R.string.txt_error,
					R.string.txt_have_no_schedule);
		}

	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		// Calendar c = Calendar.getInstance();
		// int hour = c.get(Calendar.HOUR_OF_DAY);
		// int minute = c.get(Calendar.MINUTE);

		switch (view.getId()) {
		case R.id.activity_schedule_base_img_picker_time_on:
			// Get Current time System
			String[] time = ((String) tvPickertimeOn.getText()).split(":");
			int hour = Integer.valueOf(time[0]);
			int minute = Integer.valueOf(time[1]);
			TimepickDialog(getApplicationContext(), hour, minute, true);
			break;
		case R.id.activity_schedule_base_tv_picker_time_on:
			String[] time1 = ((String) tvPickertimeOn.getText()).split(":");
			int hour1 = Integer.valueOf(time1[0]);
			int minute1 = Integer.valueOf(time1[1]);
			TimepickDialog(getApplicationContext(), hour1, minute1, true);
			break;
		case R.id.activity_schedule_base_img_picker_time_off:
			String[] time2 = ((String) tvPickertimeOff.getText()).split(":");
			int hour2 = Integer.valueOf(time2[0]);
			int minute2 = Integer.valueOf(time2[1]);
			TimepickDialog(getApplicationContext(), hour2, minute2, false);
			break;
		case R.id.activity_schedule_base_tv_picker_time_off:
			String[] time3 = ((String) tvPickertimeOff.getText()).split(":");
			int hour3 = Integer.valueOf(time3[0]);
			int minute3 = Integer.valueOf(time3[1]);
			TimepickDialog(getApplicationContext(), hour3, minute3, false);
			break;
		}
	}

	public class EditScheduleReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public EditScheduleReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			unregisterReceiver(this);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_edit_schedule_successful)))
				finish();

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_edit_schedule_failed)))
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);
			else if (intent.getAction() == context
					.getString(R.string.txt_broadcast_edit_schedule_overload)) {

				showCustomDialog(R.string.txt_error,
						R.string.txt_error_overload_schedule_HC);
			}
		}

	}

	public class DeleteScheduleReceiver extends BroadcastReceiver {

		private ProgressDialog mDialog;

		public DeleteScheduleReceiver(ProgressDialog dialog) {
			mDialog = dialog;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			mDialog.cancel();
			unregisterReceiver(this);
			if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_del_schedule_sucessful))) {

			}

			else if (intent
					.getAction()
					.equals(context
							.getString(R.string.txt_broadcast_del_schedule_failed)))
				showCustomDialog(R.string.txt_error,
						R.string.txt_error_cannot_connect_HC);

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android
	 * .support.v4.content.Loader, java.lang.Object)
	 */
	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
		cursor.moveToFirst();
		oldScheduleState = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.STATE));
		this.mOldTurnOnHour = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.HOUR));

		this.mOldTurnOnMinute = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.MINUTE));
		this.mOldTurnOffHour = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.HOUR_END));
		this.mOldTurnOffMinute = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.MINUTE_END));
		this.mOldRepeat = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.REPEAT));
		this.mOldMonday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.MONDAY));
		this.mOldTuesday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.TUESDAY));
		this.mOldWednesday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.WEDNESDAY));
		this.mOldThursday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.THURSDAY));
		this.mOldFriday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.FRIDAY));
		this.mOldSaturday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.SATURDAY));
		this.mOldSunday = cursor.getInt(cursor
				.getColumnIndex(TBL_Schedule.SUNDAY));
		this.mOldDeviceState = cursor.getInt(cursor
				.getColumnIndex(TBL_DeviceState.VALUE));

		init_data();
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub

	}

	public void showCustomDialog(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvTitle = new TextView(getApplicationContext());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
		// TODO Auto-generated method stub
		int scheduleID = bundle.getInt(SCHEDULE_ID);
		String selection = TBL_Schedule._ID + "=?";
		String[] selectionArgs = new String[] { scheduleID + "" };
		return new CursorLoader(getApplicationContext(),
				TBL_Schedule.CONTENT_URI_SCHEDULE_DEVICE, null, selection,
				selectionArgs, null);
	}

	// ==============================Cac ham ve thu=======================
	public void setT2(boolean isOn) {
		mT2 = isOn;
		Log.e("setT2", "" + isOn);
	}

	public boolean getT2() {
		Log.e("getT2", "" + mT2);
		return mT2;
	}

	public void setT3(boolean isOn) {
		mT3 = isOn;
	}

	public boolean getT3() {
		return mT3;
	}

	public void setT4(boolean isOn) {
		mT4 = isOn;
	}

	public boolean getT4() {
		return mT4;
	}

	public void setT5(boolean isOn) {
		mT5 = isOn;
	}

	public boolean getT5() {
		return mT5;
	}

	public void setT6(boolean isOn) {
		mT6 = isOn;
	}

	public boolean getT6() {
		return mT6;
	}

	public void setT7(boolean isOn) {
		mT7 = isOn;
	}

	public boolean getT7() {
		return mT7;
	}

	public void setCn(boolean isOn) {
		mCn = isOn;
	}

	public boolean getCn() {
		return mCn;
	}

	// -----------------------------------------------------------------------
	private class MyAdapter extends BaseAdapter {
		private int mSize = 7;

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 1;
		}

		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getApplicationContext(),
						R.layout.item_listview_base_schedule, null);
				ViewHolder viewholder = new ViewHolder();
				viewholder.tv = (TextView) convertView
						.findViewById(R.id.item_listview_base_schedule_tv);
				viewholder.tgb = (ToggleButton) convertView
						.findViewById(R.id.item_listview_base_schedule_check);
				viewholder.linear = (LinearLayout) convertView
						.findViewById(R.id.item_listview_base_schedule_linear);
				convertView.setTag(viewholder);
			}
			final ViewHolder holder = (ViewHolder) convertView.getTag();
			switch (position) {
			case 0:
				holder.tv.setText(getString(R.string.txt_monday_full));
				if (getT2()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT2", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT2false", "1:" + position);
					Log.e("checkT2false", "1:" + holder.tgb.isChecked());
				}
				break;
			case 1:
				holder.tv.setText(getString(R.string.txt_tuesday_full));
				if (getT3()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT3", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT3false", "1:" + position);
				}
				break;
			case 2:
				holder.tv.setText(getString(R.string.txt_wenesday_full));
				if (getT4()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT4", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT4false", "1:" + position);
				}
				break;
			case 3:
				holder.tv.setText(getString(R.string.txt_thursday_full));
				if (getT5()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT5", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT5false", "1:" + position);
				}
				break;
			case 4:
				holder.tv.setText(getString(R.string.txt_friday_full));
				if (getT6()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT6", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT6false", "1:" + position);
				}
				break;
			case 5:
				holder.tv.setText(getString(R.string.txt_saturday_full));
				if (getT7()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkT7", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkT7false", "1:" + position);
				}
				break;
			case 6:
				holder.tv.setText(getString(R.string.txt_sunday_full));
				if (getCn()) {
					holder.tgb.setBackgroundResource(R.drawable.img_tickon);
					Log.e("checkCn", "1:" + position);
				} else {
					holder.tgb.setBackgroundResource(R.drawable.img_tickoff);
					Log.e("checkCnfalse", "1:" + position);
				}
				break;
			default:
				break;
			}

			holder.tgb
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							if (Config.isVibrate)
								new VibrateThread(getApplicationContext())
										.start();
							if (isChecked) {
								buttonView
										.setBackgroundResource(R.drawable.img_tickon);
								switch (position) {
								case 0:
									Log.e("checkT2CheckTrue", "1:" + position);
									setT2(true);
									break;
								case 1:
									setT3(true);
									break;
								case 2:
									setT4(true);
									break;
								case 3:
									setT5(true);
									break;
								case 4:
									setT6(true);
									break;
								case 5:
									setT7(true);
									break;
								case 6:
									Log.e("checkCnCheckTrue", "1:" + position);
									setCn(true);
									break;
								}
							} else {
								buttonView
										.setBackgroundResource(R.drawable.img_tickoff);
								switch (position) {
								case 0:
									Log.e("checkT2CheckFalse", "1:" + position);
									setT2(false);
									break;
								case 1:
									setT3(false);
									break;
								case 2:
									setT4(false);
									break;
								case 3:
									setT5(false);
									break;
								case 4:
									setT6(false);
									break;
								case 5:
									setT7(false);
									break;
								case 6:
									Log.e("checkCnCheckFalse", "1:" + position);
									setCn(false);
									break;
								}
							}
						}
					});
			holder.linear.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(getApplicationContext()).start();
					switch (position) {
					case 0:
						if (!getT2()) {
							setT2(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT2(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}

						break;
					case 1:
						if (!getT3()) {
							setT3(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT3(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 2:
						if (!getT4()) {
							setT4(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT4(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 3:
						if (!getT5()) {
							setT5(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT5(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 4:
						if (!getT6()) {
							setT6(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT6(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 5:
						if (!getT7()) {
							setT7(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setT7(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					case 6:
						if (!getCn()) {
							setCn(true);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickon);
						} else {
							setCn(false);
							holder.tgb
									.setBackgroundResource(R.drawable.img_tickoff);
						}
						break;
					}
				}
			});

			return convertView;
		}

	}

	public void showCustomDialogBoth(int title, int message) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));

		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvTitle = new TextView(getApplicationContext());
		tvTitle = changeFont.changeFontTextView(tvTitle, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvTitle);
		ErrorDialog.setMessage(message);
		// ErrorDialog.setPositiveButton("Tiếp tục",
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.cancel();
		// finish();
		// }
		// });
		ErrorDialog.setNegativeButton(R.string.glb_txt_return,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						dialog.cancel();

					}
				});
		;
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		alertErrorDialog.getWindow().getAttributes();
		TextView tvMessage = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		tvMessage = changeFont.changeFontTextView(tvMessage, message,
				LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
				getResources().getColor(R.color.greenLight));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.fontBold));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);

	}

	public static class ViewHolder {
		public LinearLayout linear;
		public TextView tv;
		public ToggleButton tgb;
	}

	private void TimepickDialog(Context cons, int curHours, int curMinutes,
			final boolean isOn) {
		View view = getLayoutInflater()
				.inflate(R.layout.dialog_wheeltime, null);

		// hours wheel
		final TimePicker timePicker = (TimePicker) view
				.findViewById(R.id.timePicker);
		timePicker.setIs24HourView(true);

		final Button save = (ButtonCustom) view
				.findViewById(R.id.dialog_wheeltime_save);
		final Button cancel = (ButtonCustom) view
				.findViewById(R.id.dialog_wheeltime_cancel);

		AlertDialog.Builder alert = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));
		TextView title = new TextView(this);
		ChangeFont fontTitle = new ChangeFont(getApplicationContext());
		title = fontTitle.changeFontTextView(title, R.string.txt_picker_time,
				LumiHome.font, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		alert.setCustomTitle(title);

		alert.setView(view);
		alert.setCancelable(false);

		final AlertDialog dialog = alert.create();
		dialog.show();

		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				if (isOn) {
					mNewTurnOnHour = timePicker.getCurrentHour();
					mNewTurnOnMinute = timePicker.getCurrentMinute();
					tvPickertimeOn.setText(AbstractSceneActivity
							.padding_str(mNewTurnOnHour)
							+ ":"
							+ AbstractSceneActivity
									.padding_str(mNewTurnOnMinute));

				}

				else {
					mNewTurnOffHour = timePicker.getCurrentHour();
					mNewTurnOffMinute = timePicker.getCurrentMinute();
					tvPickertimeOff.setText(AbstractSceneActivity
							.padding_str(mNewTurnOffHour)
							+ ":"
							+ AbstractSceneActivity
									.padding_str(mNewTurnOffMinute));
				}
				dialog.cancel();
				return;
			}
		});
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				dialog.cancel();
				return;
			}
		});

		// set time
		timePicker.setCurrentHour(curHours);
		timePicker.setCurrentMinute(curMinutes);

	}

}
